//
//  LanguageUICheckedViewController.swift
//  
//
//  Created by CSS on 8/17/23.
//

import UIKit

@objc(CSLanguageUICheckedViewController)
public class LanguageUICheckedViewController: UIViewController {

    private var collectionView: UICollectionView!
    private var flowlayout: UICollectionViewFlowLayout!
    
    private var languageNames: [String] = ["Localizable"]
    private var customLanguageNames: [Bundle:String] = [:]
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "选择要测试的语言"
        navigationItem.backButtonTitle = "返回"
        
        if let navigationController, navigationController.viewControllers.count == 1 {
            navigationItem.leftBarButtonItem = .init(title: "返回", style: .plain, target: self, action: #selector(dismissButtonAction(_:)))
        }
        
        view.backgroundColor = .init(white: 240 / 255.0, alpha: 1.0)
        collectionViewSetup()
    }
    
}

// MARK: UICollectionView 处理类
extension LanguageUICheckedViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    private func collectionViewSetup() {
        flowlayout = HomeCollectionFlowlayout()
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowlayout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        view.addSubview(collectionView)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            collectionView.topAnchor.constraint(equalTo: view.topAnchor)
        ])
        
        collectionView.register(.init(nibName: "HomeLanguageCell", bundle: .module), forCellWithReuseIdentifier: "HomeLanguageCell")
        
        flowlayout.sectionInset = .init(top: 20, left: 12, bottom: 20, right: 12)
        flowlayout.minimumLineSpacing = 8
        flowlayout.minimumInteritemSpacing = 10
    }
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        LanguageType.allCases.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeLanguageCell", for: indexPath) as! HomeLanguageCell
        cell.languageType = .languageType(withIndex: indexPath.row)
        return cell
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let languageType = LanguageType.languageType(withIndex: indexPath.row)
        return HomeLanguageCell.cellSize(withValue: languageType.languageName)
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        UIBarButtonItem.appearance(whenContainedInInstancesOf: [LanguageSearchBar.self]).tintColor = .systemBlue
        UIBarButtonItem.appearance(whenContainedInInstancesOf: [LanguageSearchBar.self]).title = "取消"
        let resultsVC = LanguageUIResultsViewController(nibName: "LanguageUIResultsViewController", bundle: .module)
        resultsVC.languageNames = languageNames
        resultsVC.customLanguageNames = customLanguageNames
        resultsVC.languageType = .languageType(withIndex: indexPath.row)
        navigationController?.pushViewController(resultsVC, animated: true)
    }
    
}

// MARK: 事件处理类方法
@objc private extension LanguageUICheckedViewController {
    func dismissButtonAction(_ sender: Any) {
        dismiss(animated: true)
    }
}


// MARK: 对外访问类
public extension LanguageUICheckedViewController {
    
    @objc class func present(fromViewController viewController: UIViewController) {
        present(fromViewController: viewController, languageNames: ["Localizable"])
    }
    
    @objc class func present(fromViewController viewController: UIViewController, languageNames: [String] = ["Localizable"]) {
        present(fromViewController: viewController, languageNames: languageNames, customLanguageNames: [])
    }
    
    @objc class func present(fromViewController viewController: UIViewController, languageNames: [String] = ["Localizable"], customLanguageNames: [String]) {
        let checkedVC = LanguageUICheckedViewController()
        checkedVC.languageNames = languageNames
        checkedVC.customLanguageNames = customLanguageNames.reduce([:], { partialResult, languageName in
            if let bundle: Bundle = .bundle(forCustomLanguageName: languageName) {
                return partialResult + [bundle:languageName]
            }
            return partialResult
        })
        let navCheckedVC = UINavigationController(rootViewController: checkedVC)
        navCheckedVC.navigationBar.barTintColor = .white
        if UIDevice.current.userInterfaceIdiom == .pad {
            var presentVC = viewController
            if let parentVC = viewController.parent {
                presentVC = parentVC
            }
            if presentVC.modalPresentationStyle == .formSheet || presentVC.modalPresentationStyle == .currentContext ||
                presentVC.modalPresentationStyle == .overCurrentContext {
                navCheckedVC.modalPresentationStyle = .overCurrentContext
            } else {
                navCheckedVC.modalPresentationStyle = .formSheet
            }
        } else {
            navCheckedVC.modalPresentationStyle = .fullScreen
        }
        
        viewController.present(navCheckedVC, animated: true)
    }
    
    @objc class func push(withNavigationController navigationController: UINavigationController?) {
        push(withNavigationController: navigationController, languageNames: ["Localizable"])
    }
    
    @objc class func push(withNavigationController navigationController: UINavigationController?, languageNames: [String] = ["Localizable"]) {
        push(withNavigationController: navigationController, languageNames: languageNames, customLanguageNames: [])
    }
    
    @objc class func push(withNavigationController navigationController: UINavigationController?, languageNames: [String] = ["Localizable"], customLanguageNames: [String]) {
        guard let navigationController else {
            return
        }
        let checkedVC = LanguageUICheckedViewController()
        checkedVC.hidesBottomBarWhenPushed = true
        checkedVC.languageNames = languageNames
        checkedVC.customLanguageNames = customLanguageNames.reduce([:], { partialResult, languageName in
            if let bundle: Bundle = .bundle(forCustomLanguageName: languageName) {
                return partialResult + [bundle:languageName]
            }
            return partialResult
        })
        navigationController.pushViewController(checkedVC, animated: true)
    }
    
}

extension Bundle {
    class func bundle(forCustomLanguageName languageName: String) -> Bundle? {
        for bundle in allBundles {
            let sourcePath = bundle.bundlePath + "/zh-Hans.lproj/\(languageName).strings"
            if FileManager.default.fileExists(atPath: sourcePath) {
                return bundle
            }
        }
        return nil
    }
}

extension Dictionary {
    static func + (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
        var result = lhs
        rhs.forEach { result[$0.key] = $0.value }
        return result
    }
}
